// 引入 QCloud 小程序增强 SDK
var qcloud = require('../../vendor/qcloud-weapp-client-sdk/index');

// 引入配置
var config = require('../../config');
var util = require('../../utils/util');

// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
});

// 显示成功提示
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
});

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: JSON.stringify(content),
        showCancel: false
    });
};

Page({
    data: {
        messageId: null,
        message: null,
        distance:'',
        comments: [],
        submitCommentUrl: config.service.submitCommentUrl,
        messageDetailUrl: config.service.messageDetailUrl,
        reportMessageUrl: config.service.reportMessageUrl,
        dolikeUrl: config.service.dolikeUrl,
        comment: '',
        toView: '',
        showImages: [],
        isShowImages: false,
        textAreaFocus: false,
        replyCommentId: null,
        textAreaPlaceholder: '评论',
        showInputCommentError: false
    },
    onLoad: function (options) {
        // 生命周期函数--监听页面加载
        this.data.messageId = options.messageid;
        var messages = wx.getStorageSync('messages');
        for (let i = 0; i < messages.length; i++) {
            let message = messages[i];
            if (message.message.id == this.data.messageId) {
                this.data.message = message;
                break;
            }
        }
        this.data.distance = this.data.message.distance;
        this.setData({
            message: this.data.message,
            distance: this.data.distance
        });
    },
    onReady: function () {
        // 生命周期函数--监听页面初次渲染完成
    },
    onShow: function () {
        // 生命周期函数--监听页面显示
        console.log("onshow");

        this.loadDetailMessage(this.data.messageId);
    },
    onHide: function () {
        // 生命周期函数--监听页面隐藏

    },
    onUnload: function () {
        // 生命周期函数--监听页面卸载

    },
    onPullDownRefresh: function () {
        // 页面相关事件处理函数--监听用户下拉动作

    },
    onReachBottom: function () {
        // 页面上拉触底事件的处理函数

    },
    onShareAppMessage: function () {
        // 用户点击右上角分享
        return {
            title: 'title', // 分享标题
            desc: 'desc', // 分享描述
            path: 'path' // 分享路径
        }
    },
    hideInputCommentError() {
        this.data.showInputCommentError = false;
        this.setData({
            showInputCommentError: false
        });
    },
    doReply: function () {
        var that = this;
        var comment = this.data.comment;
        if (comment.length == 0) {
            this.data.showInputCommentError = true;
            this.setData({
                showInputCommentError: true
            });
            setTimeout(function () {
                that.hideInputCommentError();
            }, 2500);
            return;
        }

        var messageId = that.data.messageId;
        var userInfo = wx.getStorageSync('userInfo');
        var userId = userInfo.userId;
        var userName = userInfo.nickName;
        var avatarUrl = userInfo.avatarUrl;
        var gender = userInfo.gender;
        var data = {
            messageId: messageId,
            comment: comment,
            userId: userId,
            userName: userName,
            avatarUrl: avatarUrl,
            gender: gender
        };

        if(that.data.replyCommentId != null){
            data.replyCommentId = that.data.replyCommentId;
        }

        qcloud.request({
            // 要请求的地址
            url: that.data.submitCommentUrl,
            data: data,
            method: 'POST',
            // 请求之前是否登陆，如果该项指定为 true，会在请求之前进行登录
            login: true,
            success(result) {
                that.data.comment = '';
                that.setData({
                    comment: that.data.comment
                });
                showSuccess('评论成功');
                console.log('request success', result);
                // indexObj
                result = result.data.result;
                that.data.comments = result;
                that.data.message.comments = that.data.comments;
                that.data.message.message.comment = that.data.comments.length;


                var messages = wx.getStorageSync('messages');
                for (let i = 0; i < messages.length; i++) {
                    let message = messages[i];
                    if (message.message.id == that.data.messageId) {
                        message = that.data.message;
                        break;
                    }
                }
                wx.getStorageSync('messages', messages);

                for (let i = 0; i < that.data.comments.length; i++) {
                    var comment = that.data.comments[i];
                    comment.time = util.formatTime(new Date(comment.createdAt));
                    
                    if(comment.replyCommentId != null){
                        for (let j = 0; j < that.data.comments.length; j++) {
                            var comment2 = that.data.comments[j];
                            if(comment.replyCommentId == comment2.id){
                                comment.replayName='回复 '+comment2.userName+":";
                            }
                        }
                    }
                }

                that.setData({
                    message: that.data.message
                });
                var lastComment = that.data.message.comments[that.data.message.comments.length - 1];
                that.data.toView = "comment-" + lastComment.id;
                that.setData({
                    toView: that.data.toView
                });
            },
            fail(error) {
                showModel('请求失败', error);
                console.log('request fail', error);
            },
            complete() {
                console.log('request complete');
            }
        });
    },
    inputComment: function (e) {
        var value = e.detail.value;
        this.data.comment = value;

    },
    loadDetailMessage(messageId) {
        var that = this;
        var userInfo = wx.getStorageSync('userInfo');
        var userId = userInfo.userId;
        var data = { messageId: messageId, userId: userId }

        qcloud.request({
            // 要请求的地址
            url: that.data.messageDetailUrl,
            data: data,
            method: 'GET',
            success(result) {
                console.log('request success', result);
                result = result.data.result;
                that.data.message = result;
                that.data.comments = that.data.message.comments;
                for (let i = 0; i < that.data.comments.length; i++) {
                    var comment = that.data.comments[i];
                    comment.time = util.formatTime(new Date(comment.createdAt));

                    if(comment.replyCommentId != null){
                        for (let j = 0; j < that.data.comments.length; j++) {
                            var comment2 = that.data.comments[j];
                            if(comment.replyCommentId == comment2.id){
                                comment.replayName='回复 '+comment2.userName+":";
                            }
                        }
                    }
                }

                that.setData({
                    message: that.data.message
                });

            },
            fail(error) {
                showModel('请求失败', error);
                console.log('request fail', error);
            },
            complete() {
                console.log('request complete');
            }
        });
    },

    tapComment(e) {
        var commentid = e.currentTarget.dataset.commentid;
        var name = e.currentTarget.dataset.username;
        this.data.replyCommentId = commentid;
        // 修改默认的占位内容
        this.data.textAreaPlaceholder = "回复" + name + ":";

        this.setData({
            textAreaPlaceholder: this.data.textAreaPlaceholder,
            textAreaFocus: true
        });
    },
    stopEdit(e) {
        // 滑动的时候，editing = no
        this.data.textAreaFocus = false;
        this.data.textAreaPlaceholder = '评论';
        this.data.replyCommentId = null;

        this.setData({
            textAreaFocus: this.data.textAreaFocus,
            textAreaPlaceholder: this.data.textAreaPlaceholder
        });
    },
    /**
     * 点击查看图片
     */
    showImages(e) {
        var index = e.currentTarget.dataset.index;
        var messageItem = this.data.message;
        this.data.showImages = messageItem.images;

        var that = this;

        that.setData({
            showImages: messageItem.images,
            isShowImages: true
        });
    },
    doComment(){
        this.stopEdit();
        this.data.textAreaFocus = true;
        this.data.textAreaPlaceholder = '评论';
        this.setData({
            textAreaFocus: this.data.textAreaFocus,
            textAreaPlaceholder: this.data.textAreaPlaceholder
        });
    },
    /**
     * 关闭查看图片
     */
    closeShowView() {
        var that = this;
        that.setData({
            isShowImages: false
        });
    },
    /**
     * 点击支持
     */
    doSupport(e) {
        var that = this;
        // showBusy('点赞...');
        var messageid = e.currentTarget.dataset.messageid;
        var enablelike = e.currentTarget.dataset.enablelike

        var like = 1;
        if (enablelike == 0) {
            enablelike = 1;
            like = 0;
        } else {
            enablelike = 0;
        }

        var userInfo = wx.getStorageSync('userInfo');
        var userId = userInfo.userId;
        // 请求服务端，支持当前的请求
        var data = {
            messageId: messageid,
            userId: userId,
            like: like
        };

        qcloud.request({
            // 要请求的地址
            url: this.data.dolikeUrl,
            data: data,
            method: 'POST',
            success(result) {
                // showSuccess('请求成功完成');
                var result = result.data.result;
                // data.result.likeCount | messageid

                that.data.message.message.likes = result.likeCount;
                that.data.message.enableLike = enablelike;

                var messages = wx.getStorageSync('messages');
                for(let i=0; i<messages.length; i++){
                    var item = messages[i];
                    if(item.id = messageid){
                        item.likes = result.likeCount;
                        item.enableLike = enablelike;
                        break;
                    }
                }
                wx.setStorageSync('messages', messages);
                that.setData({
                    message: that.data.message
                });
            },
            fail(error) {
                showModel('请求失败', error);
                console.log('request fail', error);
            },
            complete() {
                console.log('request complete');
            }
        });
    },
    doReport(e) {
        var that = this;
        var messageid = e.currentTarget.dataset.messageid;
        var userid = e.currentTarget.dataset.userid;

        wx.showModal({
            title: '举报',
            content: '该动态存内容不合法，我要举报！',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    showBusy('正在处理');
                    var data = { messageId: messageid, userId: userid }
                    // 
                    qcloud.request({
                        // 要请求的地址
                        url: that.data.reportMessageUrl,
                        data: data,
                        method: 'POST',
                        success(result) {
                            // showSuccess('请求成功完成');
                            var result = result.data.result;
                            // data.result.likeCount | messageid
                            showSuccess('举报成功');
                            
                        },
                        fail(error) {
                            showModel('请求失败', error);
                            console.log('request fail', error);
                        },
                        complete() {
                            console.log('request complete');
                        }
                    });
                }
            }
        })

    }
})